<!--  -->
<template>
  <div class>
    <el-switch v-model="isDraggable" active-text="开启拖拽" inactive-text="关闭拖拽"></el-switch>
    <el-tree
      :data="data"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      :draggable="isDraggable"
      :allow-drop="allowDrop"
      @node-drag-end="nodeDragEnd"
      :default-expanded-keys="expandedKeys"
      node-key="catId"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level<=2"
            type="text"
            size="mini"
            @click="() => dialogShow(data,'add')"
          >Append</el-button>
          <el-button type="text" size="mini" @click="() => dialogShow(data,'edit')">Edit</el-button>
          <el-button
            v-if="node.childNodes.length==0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >Delete</el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog :title="title" :visible.sync="isAppend">
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isAppend = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    return {
      data: [],
      isDraggable: false,
      isAppend: false,
      title: "",
      dialogType: "", //弹框类型
      updateData: [],
      category: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 0,
        sort: 0,
        productCount: 0,
      },
      defaultProps: {
        children: "children",
        label: "name",
      },
      expandedKeys: [],
    };
  },
  methods: {
    //判断当前节点是否可以被放置
    allowDrop(draggingNode, dropNode, type) {
      if (type === "inner") {
        return dropNode.level + this.countLevel(draggingNode.data) < 3;
      } else {
        return dropNode.level + this.countLevel(draggingNode.data) <= 3;
      }
    },
    //统计当前节点最深层级
    countLevel(data) {
      let levelNum = 0;
      let temp = 0;
      if (data.children != null && data.children.length > 0) {
        levelNum = levelNum + 1;
        for (let i = 0; i < data.children.length; i++) {
          let num = this.countLevel(data.children[i]);
          temp = num > temp ? num : temp;
        }
      }
      return levelNum + temp;
    },
    nodeDragEnd(node, dragNode, type, event) {
      //获取父节点
      let parent = {};
      if (type === "inner") {
        parent = dragNode;
      } else {
        parent = dragNode.parent;
      }
      let childNodes = parent.childNodes;
      //遍历子节点 取出排序
      for (let i = 0; i < childNodes.length; i++) {
        if (childNodes[i].data.catId === node.data.catId) {
          this.updateData.push({
            catId: childNodes[i].data.catId,
            sort: i,
            parentCid: parent.data.catId === undefined ? 0 : parent.data.catId,
            catLevel: parent.level + 1,
          });
          this.childrenLevel(childNodes[i], parent.level + 1);
        } else {
          this.updateData.push({ catId: childNodes[i].data.catId, sort: i });
        }
      }
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateData, false),
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "修改成功!",
        });
        this.updateData = [];
        this.expandedKeys = [parent.data.catId];
        this.getMenu();
      });

      console.log(this.updateData);
      console.log(node, dragNode, type);
    },

    childrenLevel(node, level) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          this.updateData.push({
            catId: node.childNodes[i].data.catId,
            catLevel: level + 1,
          });
          this.childrenLevel(node.childNodes[i], level + 1);
        }
      }
    },

    // handleNodeClick(data) {
    //   console.log(data);
    // },
    dialogShow(data, dialogType) {
      this.dialogType = dialogType;
      if (dialogType == "add") {
        this.openAppend(data);
      } else {
        this.openEdit(data);
      }
    },
    openEdit(data) {
      console.log(data);
      this.title = "修改分类";
      this.isAppend = true;
      //教程中推荐在服务器重新查一遍，但是我懒
      this.category.name = data.name;
      this.category.catId = data.catId;
      this.category.parentCid = data.parentCid;
    },
    openAppend(data, dialogType) {
      this.title = "新增分类";
      this.category.name = "";
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      this.category.showStatus = 1;
      this.category.sort = 0;
      this.category.productCount = 0;
      this.isAppend = true;
    },
    submit() {
      if (this.dialogType == "add") {
        this.append();
      } else {
        this.edit();
      }
    },
    edit() {
      let { catId, name } = this.category;
      let data = { catId, name };
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData(data, false),
      })
        .then(({ data }) => {
          this.$message({
            type: "success",
            message: "修改成功!",
          });
          this.expandedKeys = [this.category.parentCid];
          this.getMenu();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "修改失败",
          });
        });
      this.isAppend = false;
    },
    append() {
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      })
        .then(({ data }) => {
          this.$message({
            type: "success",
            message: "添加成功!",
          });
          this.expandedKeys = [this.category.parentCid];
          this.getMenu();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "添加失败",
          });
        });
      this.isAppend = false;
    },
    remove(node, data) {
      let ids = [data.catId];
      this.$confirm(`将要删除【${data.name}】菜单, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.expandedKeys = [node.parent.data.catId];
            this.getMenu();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      console.log(node, data);
    },
    getMenu() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        console.log("菜单数据=>" + data.entities);
        this.data = data.entities;
      });
    },
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getMenu();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
</style>